<template>
  <div class="index-container">
    <div class="main-header">
      <el-row>
        <el-col :xs="18" :sm="18" :md="18" :lg="18" :xl="18">
          <div class="nav">
            <ul>
              <li
                v-for="(item, index) in sub_class"
                :key="index"
                :class="{ active: classActive == item.id }"
                :data-id="item.id"
                @click="handleClass"
              >
                {{ item.name }}
              </li>
            </ul>
          </div>
        </el-col>
        <el-col v-if="userpermi.includes(64)" :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
          <div class="fr">
            <el-button
              size="medium"
              type="danger"
              icon="el-icon-delete"
              style="margin-left: 20px;"
              @click="handleDeleteVideo"
            >
              {{ !isdelete ? "删 除" : "取 消" }}
            </el-button>
          </div>
          <div class="fr">
            <el-button
              size="medium"
              type="primary"
              icon="el-icon-plus"
              @click="handleVideoUpload"
            >
              新 增
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="main-content">
      <div class="video-main">
        <ul class="clearfix">
          <li
            v-for="(item, index) in pageData.list"
            :key="index"
            :data-video="item.path"
            :data-img="item.cover"
            :data-title="item.title"
            :data-id="item.id"
            :data-index="index"
            @click="playVideo"
          >
            <div class="videoThumb">
              <img :src="item.cover" alt="" />
              <p
                v-if="isdelete"
                class="deleteBtn"
                @click.stop="handleDelete(item.id)"
              >
                <i class="el-icon-delete"></i>
              </p>
              <span class="pageView">
                <i class="el-icon-view"></i>
                {{ item.page_view }}
              </span>
              <span class="longTime">{{ item.length }}s</span>
            </div>

            <div class="videoText">
              {{ item.title }}
            </div>
          </li>
        </ul>
        <el-pagination
          :background="background"
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageData.page_size"
          :total="pageData.total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      :title="viedoTitle"
      :visible.sync="dialogVisible"
      width="1720px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      class="dialogVideo"
    >
      <div class="dialog-main">
        <div class="video-container">
          <!-- <vab-player-mp4 :config="config1" @player="Player1 = $event" /> -->
          <video-player
            ref="videoPlayer"
            class="video-player vjs-custom-skin"
            :playsinline="true"
            :options="playerOptions"
          ></video-player>
        </div>
        <div class="video-list">
          <ul>
            <li
              v-for="(item, index) in sliderData"
              :key="index"
              :data-video="item.path"
              :data-img="item.cover"
              :data-title="item.title"
              :data-id="item.id"
              :data-index="index"
              :class="{ active: sliderActive == index }"
              @click="playSilderVideo"
            >
              <div class="videoThumb">
                <img :src="item.cover" alt="" />
                <p v-if="isdelete" class="deleteBtn">
                  <i class="el-icon-delete"></i>
                </p>
                <span class="pageView">
                  <i class="el-icon-view"></i>
                  {{ item.page_view }}
                </span>
                <span class="longTime">{{ item.length }}s</span>
              </div>

              <div class="videoText">
                {{ item.title }}
              </div>
            </li>
          </ul>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      title="上传视频"
      :visible.sync="dialogVisibleUpload"
      width="30%"
      :before-close="closeDialogUpload"
      :close-on-click-modal="false"
      class="dialogupload"
    >
      <div class="dialog-main">
        <el-form
          ref="videoForm"
          :model="videoForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          size="medium"
        >
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="视频标题" prop="title">
                <el-input v-model="videoForm.title"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="所属栏目" prop="sub_id">
                <el-select
                  v-model="videoForm.sub_id"
                  clearable
                  placeholder="请选择"
                  filterable
                  style="width: 100%;"
                >
                  <el-option
                    v-for="(item, index) in sub_class"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="上传视频" prop="showVideoPath">
                <el-upload
                  class="avatar-uploader"
                  :action="url + '/upload'"
                  :on-progress="uploadVideoProcess"
                  :on-success="handleVideoSuccess"
                  :before-upload="beforeUploadVideo"
                  :show-file-list="false"
                  :headers="myHeaders"
                  :data="{
                    method,
                  }"
                >
                  <video
                    v-if="videoForm.showVideoPath != '' && !videoFlag"
                    id="upvideo"
                    :src="videoForm.showVideoPath"
                    class="avatar video-avatar"
                    controls="controls"
                  >
                    您的浏览器不支持视频播放
                  </video>
                  <i
                    v-else-if="videoForm.showVideoPath == '' && !videoFlag"
                    class="el-icon-plus avatar-uploader-icon"
                  ></i>
                  <el-progress
                    v-if="videoFlag == true"
                    type="circle"
                    :percentage="videoUploadPercent"
                    style="margin-top: 7px;"
                  ></el-progress>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="视频封面" prop="imgPath">
                <el-row>
                  <el-col :xs="9" :sm="9" :md="9" :lg="9" :xl="9">
                    <img-upload
                      v-model="videoForm.imgPath"
                      tips="视频封面"
                      method="img"
                      :updisabled="false"
                      @result="resultAvatar"
                    ></img-upload>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="form-footer">
          <el-button type="primary" class="sureBtn" size="mini" @click="save">
            提 交
          </el-button>
          <el-button
            type="info"
            class="setBtn"
            size="mini"
            @click="cancel('videoForm')"
          >
            取 消
          </el-button>
        </div>
      </div>
    </el-dialog>
    <canvas id="mycanvas" class="mycanvas"></canvas>
  </div>
</template>
<script>
  import store from "@/store";
  import "video.js/dist/video-js.css";
  import { videoPlayer } from "vue-video-player";
  import { getList, getHotList } from "@/api/carevideo";
  import { baseURL } from "@/config/settings";
  import imgUpload from "@/components/AppUpload/index";
  // import $ from "jquery/dist/jquery.min.js";
  // import store from "@/store";
  import { mapGetters } from "vuex";
  export default {
    name: "Index",
    components: { videoPlayer, imgUpload },
    data() {
      return {
        pid: 1,
        sub_id: 1,
        classActive: 1,
        sliderActive: 0,
        url: baseURL,
        method: "video",
        viedoTitle: "",
        pageNo: 1,
        pageSize: 10,
        layout: "total, prev, pager, next, jumper",
        total: 0,
        background: true,
        isdelete: false,
        dialogVisible: false,
        dialogVisibleUpload: false,
        sub_class: [
          {
            name: "痛风",
            id: 1,
          },
          {
            name: "高血压",
            id: 2,
          },
          {
            name: "冠心病",
            id: 3,
          },
          {
            name: "高血糖",
            id: 4,
          },
          {
            name: "糖尿病",
            id: 5,
          },
          {
            name: "脑中风",
            id: 6,
          },
          {
            name: "老年便秘",
            id: 7,
          },
          {
            name: "帕金森",
            id: 8,
          },
          {
            name: "阿尔茨海默症",
            id: 9,
          },
          {
            name: "居家护理",
            id: 10,
          },
          {
            name: "日常护理",
            id: 11,
          },
        ],
        sliderData: [],
        pageData: {},
        myHeaders: {
          token: store.getters["user/accessToken"],
        },
        playerOptions: {
          playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
          autoplay: true, //如果true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 导致视频一结束就重新开始。
          preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: "zh-CN",
          aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [
            {
              src: "", // 路径
              type: "video/mp4", // 类型
            },
          ],
          poster: "", //你的封面地址
          // width: document.documentElement.clientWidth,
          notSupportedMessage: "此视频暂无法播放，请稍后再试", //允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true,
            durationDisplay: true,
            remainingTimeDisplay: false,
            fullscreenToggle: true, //全屏按钮
          },
        },
        videoFlag: false,
        //是否显示进度条
        videoUploadPercent: "",
        //进度条的进度，
        isShowUploadVideo: false,
        //显示上传按钮
        videoForm: {
          showVideoPath: "",
        },
        rules: {},
      };
    },
    computed: {
      ...mapGetters({
        userpermi: "user/userpermi",
      }),
    },
    created() {},
    beforeDestroy() {},
    mounted() {
      this.pid = 1;
      this.sub_id = 1;
      let params = {
        pid: this.pid,
        sub_id: this.sub_id,
      };
      this.getTableData(params);
      this.$set(this.videoForm, "pid", this.pid);
    },
    methods: {
      save() {
        this.$refs["videoForm"].validate(async (valid) => {
          if (valid) {
            if (this.videoForm.id) {
              getList("put", this.videoForm).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功",
                  });
                  let params = {
                    pid: this.pid,
                    sub_id: this.sub_id,
                  };
                  this.getTableData(params);
                  this.cancel("videoForm");
                }
              });
            } else {
              getList("post", this.videoForm).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "添加成功",
                  });
                  let params = {
                    pid: this.pid,
                    sub_id: this.sub_id,
                  };
                  this.getTableData(params);
                  this.cancel("videoForm");
                }
              });
            }
          }
        });
      },
      getTableData(data) {
        getList("get", data).then((resp) => {
          if (resp.code === 200) {
            this.pageData = resp.data;
          }
        });
      },
      cancel(formName) {
        this.dialogVisibleUpload = false;
        this.videoForm = {
          showVideoPath: "",
        };
        this.$set(this.videoForm, "pid", this.pid);
        this.$set(this.videoForm, "sub_id", this.sub_id);
        this.videoFlag = false;
        this.$refs[formName].resetFields();
      },
      closeDialogUpload() {
        this.dialogVisibleUpload = false;
        this.videoForm = {
          showVideoPath: "",
        };
        this.$set(this.videoForm, "pid", this.pid);
        this.$set(this.videoForm, "sub_id", this.sub_id);
        this.videoFlag = false;
        this.$refs["videoForm"].resetFields();
      },
      handleClass(e) {
        let id = e.currentTarget.dataset.id;
        console.log(id);
        this.classActive = id;
        this.sub_id = id;
        this.$set(this.videoForm, "sub_id", parseInt(id));
        let params = {
          pid: this.pid,
          sub_id: this.sub_id,
        };
        this.getTableData(params);
      },
      handleDelete(val) {
        this.$confirm("此操作将永久删除该视频, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            let param = {
              id: val,
            };
            getList("delete", param).then((resp) => {
              if (resp.code === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                let params = {
                  pid: this.pid,
                  sub_id: this.sub_id,
                };
                this.getTableData(params);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      handleSizeChange(val) {},
      handleCurrentChange(val) {
        let param = {
          page: val,
          pid: this.pid,
          sub_id: this.sub_id,
        };
        this.getTableData(param);
      },
      handleDeleteVideo() {
        this.isdelete = !this.isdelete;
      },
      closeDialog() {
        this.dialogVisible = false;
        setTimeout(() => {
          this.$refs.videoPlayer.player.pause();
        }, 300);
      },

      playVideo(e) {
        let video = e.currentTarget.dataset.video;
        let cover = e.currentTarget.dataset.img;
        let title = e.currentTarget.dataset.title;
        let id = e.currentTarget.dataset.id;
        let index = e.currentTarget.dataset.index;
        this.playerOptions.sources[0].src = video;
        this.playerOptions.poster = cover;
        this.dialogVisible = true;
        this.viedoTitle = title;
        // setTimeout(() => {
        //   console.log(this.$refs.videoPlayer.player.play());
        // }, 300);
        let params = {
          id: id,
        };
        let data = {
          pid: this.pid,
          sub_id: this.sub_id,
        };
        getList("get", params).then((resp) => {});

        let myTemp = this.pageData.list[index];
        getHotList("get", data).then((resp) => {
          if (resp.code === 200) {
            let data = resp.data.list;
            this.sliderData = JSON.parse(JSON.stringify(resp.data.list));
            for (let i = 0; i < data.length; i++) {
              const element = data[i];
              if (element.id == myTemp.id) {
                this.sliderData.splice(i, 1);
                this.sliderData.unshift(myTemp);
                break;
              } else {
                if (i === data.length - 1) {
                  this.sliderData.unshift(myTemp);
                }
              }
            }
          }
        });
      },
      playSilderVideo(e) {
        let video = e.currentTarget.dataset.video;
        let cover = e.currentTarget.dataset.img;
        let title = e.currentTarget.dataset.title;
        let id = e.currentTarget.dataset.id;
        let index = e.currentTarget.dataset.index;
        this.playerOptions.sources[0].src = video;
        this.playerOptions.poster = cover;
        this.dialogVisible = true;
        this.viedoTitle = title;
        this.sliderActive = index;
        let params = {
          id: id,
        };
        getList("get", params).then((resp) => {
          if (resp.code === 200) {
          }
        });
      },
      beforeUploadVideo(file) {
        console.log(file);
        let _this = this;
        let url = URL.createObjectURL(file);
        var audioElement = new Audio(url);
        audioElement.addEventListener("loadedmetadata", function () {
          let playTime = audioElement.duration; //playTime就是当前视频长度
          console.log(playTime);
          _this.$set(_this.videoForm, "length", parseInt(playTime));
        });
        var fileSize = file.size / 1024 / 1024 < 50;
        if (
          [
            "video/mp4",
            "video/ogg",
            "video/flv",
            "video/avi",
            "video/wmv",
            "video/rmvb",
            "video/mov",
          ].indexOf(file.type) == -1
        ) {
          this.$message({
            message: "请上传正确的视频格式",
            type: "warning",
          });
          return false;
        }
        if (!fileSize) {
          this.$message({
            message: "视频大小不能超过50MB",
            type: "warning",
          });
          return false;
        }
        this.isShowUploadVideo = false;
      },
      //进度条
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = file.percentage.toFixed(0) * 1;
      },
      //上传成功回调
      handleVideoSuccess(res, file) {
        this.isShowUploadVideo = true;
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        console.log(res);
        //前台上传地址
        //if (file.status == 'success' ) {
        //    this.videoForm.showVideoPath = file.url;
        //} else {
        //     layer.msg("上传失败，请重新上传");
        //}

        //后台上传地址
        if (res.code == 200) {
          this.videoForm.showVideoPath = res.data.path;
          this.$set(this.videoForm, "showVideoPath", res.data.path);
          this.$set(this.videoForm, "video_id", res.data.id);
          setTimeout(() => {
            // this.findvideocover(res.data.path);
          }, 300);
        } else {
          // layer.msg(res.Message);
          this.$message({
            message: "上传失败",
            type: "warning",
          });
        }
      },
      handleVideoUpload() {
        this.dialogVisibleUpload = true;
      },
      resultAvatar(data) {
        // console.log(data);
        this.$set(this.videoForm, "img_id", data.id);
      },
      //截取视频第一帧作为播放前默认图片
      // findvideocover(url, file) {
      //   const video = document.getElementById("upvideo"); // 获取视频对象
      //   // const video = document.createElement("video") // 也可以自己创建video
      //   video.src = url; // url地址 url跟 视频流是一样的
      //   var canvas = document.getElementById("mycanvas"); // 获取 canvas 对象
      //   const ctx = canvas.getContext("2d"); // 绘制2d
      //   video.crossOrigin = "anonymous"; // 解决跨域问题，也就是提示污染资源无法转换视频
      //   video.currentTime = 1; // 第一帧
      //   video.oncanplay = () => {
      //     canvas.width = video.clientWidth; // 获取视频宽度
      //     canvas.height = video.clientHeight; //获取视频高度
      //     // 利用canvas对象方法绘图
      //     ctx.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);
      //     // 转换成base64形式
      //     this.imgsrc = canvas.toDataURL("image/png"); // 截取后的视频封面
      //     console.log(this.imgsrc);
      //   };
      // },
    },
  };
</script>
<style lang="scss" scoped>
  .index-container {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30px !important;
    margin: 0 !important;
    background: #fff !important;

    .main-header {
      border-bottom: 1px solid #dddfe7;

      .nav {
        ul {
          li {
            float: left;
            padding-top: 20px;
            padding-bottom: 9px;
            margin-right: 40px;
            font-size: 16px;
            line-height: 24px;
            color: #333;
            cursor: pointer;

            &.active {
              color: #1791ff;
              border-bottom: 4px solid #1791ff;
            }

            &:hover {
              color: #1791ff;
              border-bottom: 4px solid #1791ff;
            }
          }
        }
      }
    }

    .main-content {
      .video-main {
        padding-top: 24px;

        ul {
          display: block;
          margin: 0 -15px !important;

          li {
            box-sizing: border-box;
            float: left;
            width: 20%;
            height: 256px;
            padding: 0 15px;
            margin-bottom: 20px;
            cursor: pointer;

            .videoThumb {
              position: relative;
              width: 100%;
              height: 196px;
              margin-bottom: 12px;
              overflow: hidden;

              img {
                width: 100%;
                height: 100%;
              }

              span {
                &.longTime {
                  position: absolute;
                  right: 16px;
                  bottom: 12px;
                  font-size: 16px;
                  color: #fff;
                }

                &.pageView {
                  position: absolute;
                  bottom: 12px;
                  left: 16px;
                  font-size: 16px;
                  color: #fff;

                  i {
                    padding-right: 5px;
                  }
                }
              }

              .deleteBtn {
                position: absolute;
                bottom: 0;
                left: 0;
                width: 100%;
                height: 48px;
                line-height: 48px;
                text-align: center;
                background: rgba(0, 0, 0, 0.6);

                /* Safari and Chrome */
                i {
                  font-size: 16px;
                  color: #fff;
                }
              }
            }

            .videoText {
              display: -webkit-box;
              overflow: hidden;
              font-size: 16px;
              line-height: 24px;
              color: #333;
              text-overflow: ellipsis;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }
          }
        }
      }
    }
  }

  @keyframes identifier {
    from {
      transform: translateY(100%);
    }

    to {
      transform: translateY(0%);
    }
  }

  .dialogVideo {
    .dialog-main {
      display: flex;

      .video-container {
        flex: 1;
        max-height: 700px;
      }

      .video-list {
        box-sizing: border-box;
        flex: 0 0 440px;
        width: 440px;
        max-height: 700px;
        padding: 0 24px;
        padding-right: 0;
        overflow: auto;

        ul {
          li {
            display: flex;
            margin-bottom: 24px;
            cursor: pointer;

            &.active {
              .videoText {
                color: #1791ff;
              }
            }

            .videoThumb {
              position: relative;
              flex: 0 0 200px;
              width: 200px;
              height: 124px;
              margin-right: 12px;

              img {
                width: 100%;
                height: 100%;
              }

              span {
                &.longTime {
                  position: absolute;
                  right: 8px;
                  bottom: 8px;
                  font-size: 14px;
                  color: #fff;
                }

                &.pageView {
                  position: absolute;
                  bottom: 8px;
                  left: 8px;
                  font-size: 14px;
                  color: #fff;

                  i {
                    padding-right: 3px;
                  }
                }
              }
            }

            .videoText {
              font-size: 16px;
              color: #333;
            }
          }
        }
      }
    }
  }

  ::v-deep {
    .video-js .vjs-big-play-button {
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  .avatar-uploader {
    ::v-deep {
      .el-upload {
        position: relative;
        overflow: hidden;
        cursor: pointer;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
      }
    }
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    line-height: 178px;
    color: #8c939d;
    text-align: center;
  }

  .form-footer {
    padding-left: 100px;
  }

  .video-avatar {
    width: 178px;
    height: 178px;
  }

  .mycanvas {
    position: absolute;
    z-index: -1;
  }
</style>
